package com.sun.showcase.utils;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class StringToDateConverter implements Converter<String, Date>{
	////yyyy-mm-dd
	private static Pattern formate1 = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");
	//yyyy-MM-dd HH:mm:ss
	private static Pattern formate2 = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}");
	
	@Override
	public Date convert(String source) {
		Matcher m = formate1.matcher(source);
		Matcher m2 = formate2.matcher(source);
		//只支持一下两种格式
		if(m.matches()){
			//yyyy-mm-dd
			return DateUtils.parse(DateUtils.format5, source);
		}else if(m2.matches()){
			//yyyy-MM-dd HH:mm:ss
			return DateUtils.parse(DateUtils.format3, source);
		}else{
			return null;
		}
		
	}

}
